<template>
    <Pop :title="$t('message.Login.title')" :show="account.popLogin" paddingType="spadding" :is-close="props.isClose"
        :is-back="false" @close="onClose">
        <v-form validate-on="submit lazy" @submit.prevent="onSubmit" class="form-width">
            <div class="tip">{{ $t("message.Login.email") }}</div>

            <JInput v-model="email" :placeholder="$t('message.Login.iptEmail')" button="" :err="err"></JInput>

            <!-- <v-text-field clearable class="j-input" :rules="emailRules" v-model="email" placeholder="请输入您的邮箱" :loading="false" color="#15181D" bg-color="#15181D"></v-text-field> -->

            <!-- <div class="check d-flex">
                <v-checkbox v-model="checkbox" :on-icon="'mdi-heart'" :off-icon="'mdi-home'" color="#F6AC2F">
                    <template v-slot:label>
                        <div class="check-tip">
                            登陆表示同意ChainingView
                            <a target="_blank" class="links" href="https://vuetifyjs.com"> 《服务条款》 </a>
                            和
                            <a target="_blank" class="links" href="https://vuetifyjs.com"> 《隐私政策》 </a>
                        </div>
                    </template>
                </v-checkbox>
            </div> -->
            <!-- <JCheckbox v-model="agree" class="agree">
                <div class="check-tip c-title-5">
                    {{ $t("message.Login.agreeTitle") }}
                    <a target="_blank" class="links" href="https://vuetifyjs.com">
                        {{ $t("message.Login.thisermsOfService") }}
                       
                    </a>
                    {{ $t("message.Login.and") }}
                    <a target="_blank" class="links" href="https://vuetifyjs.com">
                        {{ $t("message.Login.privacyPolicy") }}
                    </a>
                </div>
            </JCheckbox> -->

            <!-- <div class="ints">
                <JButton label="sure"></JButton>
                <JButton label="签到">okk</JButton>
            </div> -->

            <v-btn class="n-btn" color="primary" type="submit">
                <!-- 下一步  -->
                {{ $t("message.Login.next") }}
            </v-btn>
            <div class="no-ac">
                <!-- 还没有账户？ -->
                {{ $t("message.Login.notUser") }}
                <span class="no-rege" @click="gotoRegister">
                    <!-- 免费注册 -->
                    {{ $t("message.Login.enroll") }}
                </span>
            </div>
            <Other></Other>
        </v-form>
        <!-- <iframe :src="link" v-if="link"></iframe> -->
    </Pop>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import Star from "@/assets/Star.png";
import { useAccount } from "@/stores/account";
import Pop from "@/components/pop/index.vue";
import Other from "./Other.vue";
import { toast } from "@/components/toast/toast";
import JInput from "@/components/j-input/index.vue";
import JButton from "@/components/j-button/index.vue";
import JCheckbox from "@/components/j-checkbox/index.vue";
import { isValidEmail } from "@/comm/format";
import { get, post } from "@/comm/request";
import { URL_REGISTER_CHECK, URL_USER_EXIST } from "@/comm/api";
import { Notify } from "@/components/y-notify/script";
import i18n from "@/locals";
const emailStr = ref("");
const agree = ref(false);
const err = ref("");

onMounted(() => {
    err.value = "";
});

const props = defineProps({
    isClose: {
        type: Boolean,
        default: true
    }
})


// const isRegister = ref(true);
const account = useAccount();
const email = ref(localStorage.getItem("email") || "");
const emailRules = ref([
    (value: string) => {
        if (value) return true;
        return "E-mail is requred.";
    },
    (value: string) => {
        if (/.+@.+\..+/.test(value)) return true;
        return "E-mail must be valid.";
    }
]);

const onClose = () => {
    account.changePopLogin(false);
    err.value = "";
};

const gotoRegister = () => {
    account.changeIsBindEmail(false);
    account.changePopLogin(false);
    account.changePopRegister(true);
};
const busyAlert = () => {
    Notify.alert(i18n.global.t("message.Register.emailTime"), "warning", 3500)
}
const onSubmit = async (event: any) => {
    // if (!agree.value) {
    //     toast("请先同意用户协议")
    //     return;
    // }
    if (!isValidEmail(email.value)) {
        // err.value = "邮箱不合法";
        err.value = i18n.global.t("message.Login.illegal");
        return;
    }
    try {
        let obj: any = await post(URL_USER_EXIST, { email: email.value }, true);
        console.log("obj", obj);
        //10012 代表邮箱已经注册可以进行登录
        if (obj.code == 200) {
            localStorage.setItem("email", email!.value + "");
            const res = await event;
            console.log(res, email.value);
            if (!res.valid) return;
            account.changeEmail(email.value);
            account.changePopLogin(false);
            account.changePopLoginVerify(true);
            err.value = "";
            return;
        } else {
            // busyAlert()
            // toast(obj.info);
            err.value = obj.info;
            return;
        }
    } catch (err) {
        busyAlert()
        console.log('系统有误', err)
    }
};

const onGoogle = () => {
    const url =
        "https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/userinfo.email&include_granted_scopes=true&response_type=token&state=3EAB37D9D5310BFE&redirect_uri=http://127.0.0.1:5173/oauth/google&client_id=196315512392-h621tm4818ml5bl6ljv5lako4d17bac6.apps.googleusercontent.com";

    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const w = 400;
    const h = 400;
    const left = (windowWidth - w) / 2;
    const top = (windowHeight - h) / 2;
    window.open(url, "newWindow", `width=${w},height=${h},left=${left},top=${top}`);
    // link.value = url;
    // window.open(url, "_blank");

    // (window as any).gapi.load('auth2', () => {
    //     const auth2 = window.gapi.auth2.init({
    //         clientId: "196315512392-h621tm4818ml5bl6ljv5lako4d17bac6.apps.googleusercontent.com"
    //     })
    //     auth2.attachClickHandler(this.$refs.signinBtn, {}, googleUser => {
    //         // this.$emit('success', googleUser)
    //         console.log("googleUser", googleUser)
    //     }, error => {
    //         // this.$emit('error', error)
    //         // this.$emit('failure', error) // an alias
    //         console.log("error", error)
    //     })

    // })

    // loginGoogle()
};

function loginGoogle() {
    const gapi = (window as any).gapi;
    // 2. Initialize the JavaScript client library.
    gapi.client
        .init({
            apiKey: "AIzaSyCu5UCPMWSm71b9fArO42SVofmVEf7tczU",
            // clientId and scope are optional if auth is not required.
            clientId: "196315512392-h621tm4818ml5bl6ljv5lako4d17bac6.apps.googleusercontent.com",
            scope: "profile"
        })
        .then(function () {
            // 3. Initialize and make the API request.
            return gapi.client.request({
                path: "https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names"
            });
        })
        .then(
            function (response: any) {
                console.log(response.result);
            },
            function (reason: any) {
                console.log("Error: " + reason.result.error.message);
            }
        );
}

const link = ref("");

//響應返回
//http://127.0.0.1:5173/oauth/google#/state=3EAB37D9D5310BFE&access_token=ya29.a0AfB_byC85mjtNZXZtpOCK_I3tdVcU413XkUjO5W0vYz_A-S82oEZIuEodtI95gj2H9Bz3B55STAuIBm0a2gbp5h5QZgF2GUxYT_ZxdQTaiiCJcJlQRzqqJQOoDq-mXfPPJv6wQ3BeWI4DgsNWBmHKHxaVOgLMW3djQaCgYKAckSARISFQGOcNnCaRJ5aFqjsseX8RDxVaqTSA0169&token_type=Bearer&expires_in=3599&scope=email%20openid%20https://www.googleapis.com/auth/userinfo.email&authuser=0&prompt=consent

const checkbox = ref(true);
</script>

<style lang="less" scoped>
@import url("./index.less");


.form-width {
    width: 400px;
}

.ints {
    width: 100%;
    margin-bottom: 40px;
}

.check {
    margin-top: 48px;
}

.n-btn {
    margin-top: 40px;
    margin-bottom: 10px;
    width: 100%;
}

.no-ac {
    margin: 10px 0 30px;
}

.check-tip {
    margin-left: 10px;
}

.agree {
    margin-top: 40px;
    margin-bottom: 12px;
}
</style>
